import {
  Table,
  Tabs,
  Tag,
  Button,
  Space,
  Modal,
  Radio,
  Input,
  Form,
  Select,
  DatePicker,
  message,
  Popconfirm,
} from 'antd';
import { useState, useEffect } from 'react';
import { getList, updateOrder, selectAll } from '../../../../Api/Api';
import moment from 'moment';
const { TabPane } = Tabs;
const { TextArea, Search } = Input;
const { RangePicker } = DatePicker;
const { Option } = Select;
import './OrderIndex.less';

const title = [
  { key: '0', title: '全部' },
  { key: '1', title: '待付款' },
  { key: '2', title: '待发货' },
  { key: '3', title: '已发货' },
  { key: '4', title: '已完成' },
  { key: '5', title: '待评价' },
  { key: '6', title: '已取消' },
  { key: '7', title: '已删除' },
  { key: '8', title: '拼团中' },
  { key: '9', title: '一键退款' },
  { key: '10', title: '同意退款' },
  { key: '11', title: '拒绝退款' },
  { key: '12', title: '退款中' },
  { key: '13', title: '已退款' },
];

export default function List() {
  const [data, setData] = useState([]);
  const [all, setAll] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [hair, setHair] = useState(false);
  const [remarks, setRemarks] = useState(false);
  const [update, setUpdate] = useState(false);
  const [radio, setRadio] = useState(3);
  const [textArea, setTextArea] = useState('');
  const [nav, setNav] = useState(0);
  const [titleList] = useState(title);
  const [orderStatus, setOrderStatus] = useState(0);
  const [textAreaId, setTextAreaId] = useState({});
  const [updateName, setUpdateName] = useState('');
  function getlist(res) {
    let arr = [];
    res.map((item) => {
      const {
        clothing,
        tradeName,
        subtotal,
        specs,
        totalWares,
        totalDelivery,
        totalOrder,
        totalDiscount,
        payAmount,
        information,
        id,
        method,
        orderStatus,
        orderNumber,
        createdAt,
        headName,
        housingEstate,
        location,
        remarks,
      } = item;
      let key = id;
      let merchant = {
        clothing: clothing,
        tradeName: tradeName,
        subtotal: subtotal,
        specs: specs,
      };
      let money = {
        totalWares: totalWares,
        totalDelivery: totalDelivery,
        totalOrder: totalOrder,
        totalDiscount: totalDiscount,
        payAmount: payAmount,
      };
      arr.push({
        remarks,
        money,
        merchant,
        information,
        id,
        method,
        orderStatus,
        orderNumber,
        createdAt,
        headName,
        housingEstate,
        location,
        key,
      });
    });
    return arr;
  }

  function confirm(e) {
    console.log(e);

    updateOrder({ id: e.id, orderStatus: 9 }).then((res) => {
      message.success('一键退货成功');
    });
  }

  useEffect(() => {
    getList({ page: 1, limit: 4, where: { orderStatus: 0 } }).then((res) => {
      console.log(res, 123);
      setData(getlist(res.data.res));
      setAll(res.data.all);
    });
  }, []);

  function callback(key: any) {
    console.log(key, 7777777);
    getList({ page: 1, limit: 4, where: { orderStatus: key } }).then((res) => {
      console.log(res, 7777);
      setData(getlist(res.data.res));
      setAll(res.data.all);
      setNav(key);
      setOrderStatus(key);
    });
  }
  const onChange = (e: any) => {
    console.log('radio checked', e.target.value);
    setRadio(e.target.value);
  };

  function send() {
    console.log(radio, 123);
    let data = {
      id: textAreaId,
      orderStatus: radio,
    };
    updateOrder(data).then((res: any) => {
      console.log(res);
      message.success('发货成功');
    });
    setHair(false);
  }

  function submit() {
    let data = {
      remarks: textArea,
      id: textAreaId,
    };
    updateOrder(data).then((res: any) => {
      message.success('提交成功');
    });
    setRemarks(false);
  }

  function GetTextArea(e: any) {
    console.log(e.target.defaultValue, 111);
    setTextArea(e.target.defaultValue);
  }

  function handleChange(value: string) {
    console.log(`selected ${value}`);
  }

  function onFinish(value: any) {
    console.log(value, 123);
    let startTime = '';
    let endTime = '';
    let data = {};
    if (value.time) {
      startTime = moment(value.time[0]).format('YYYY-MM-DD HH:mm');
      endTime = moment(value.time[1]).format('YYYY-MM-DD HH:mm');
      console.log(startTime, endTime, 123);
      data = {
        startTime,
        endTime,
        ...value,
        orderStatus,
      };
      console.log(data, 123);
    } else {
      data = {
        ...value,
        orderStatus,
      };
    }
    getList({ page: 1, limit: 4, where: data }).then((res) => {
      console.log(res, 123);

      setData(getlist(res.data.res));
      setAll(res.data.all);
    });
  }

  function show(e: any, value: any) {
    console.log(value, 123);
    switch (e) {
      case '1':
        setHair(true);
        setTextAreaId(value.id);
        return;
      case '2':
        setRemarks(true);
        setTextAreaId(value.id);
        return;
      case '3':
        let where = {
          page: 1,
          limit: 5,
          where: { name: value.information.name },
        };
        selectAll(where).then((res: any) => {
          console.log(res, 7777777);
          setDataSource(res.result);
          setUpdateName(value.information.name);
        });
        setUpdate(true);
        return;
    }
  }

  function handleCancel(e: any) {
    switch (e) {
      case '1':
        setHair(false);
        return;
      case '2':
        setRemarks(false);
        return;
      case '3':
        setUpdate(false);
        return;
    }
  }

  function CheckChange(e) {
    console.log(e, 123);
    getList({ page: e, limit: 4, where: { orderStatus: nav } }).then((res) => {
      setData(getlist(res.data.res));
    });
  }

  const pagination = {
    total: all,
    pageSize: 4,
    defaultCurrent: 1,
    onChange: CheckChange,
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    {
      title: '商家信息',
      dataIndex: 'merchant',
      key: 'merchant',
      render: (record: any) => {
        return (
          <>
            <div>商品名称:{record.tradeName}</div>
            <div>
              图片: <img width="40" height="20" src={record.clothing} alt="" />
            </div>
            <div>
              小计:￥<span style={{ color: 'red' }}>{record.subtotal}</span>
            </div>
            <div>规格:{record.specs}</div>
          </>
        );
      },
    },
    {
      title: '买家信息',
      dataIndex: 'information',
      key: 'information',
      render: (record: any) => {
        return (
          <>
            <div>昵称:{record.nickname}</div>
            <div>姓名:{record.name}</div>
            <div>电话:{record.phone}</div>
            <div>地址:{record.address}</div>
          </>
        );
      },
    },
    { title: '送货方式', dataIndex: 'method', key: 'method' },
    {
      title: '支付金额',
      dataIndex: 'money',
      key: 'money',
      render: (record: any) => {
        return (
          <>
            <div>商品总价: {record.totalWares}</div>
            <div>配送费用: {record.totalDelivery}</div>
            <div>订单总价: {record.totalOrder}</div>
            <div>总优惠: {record.totalDiscount}</div>
            <div>
              实付金额:
              <span style={{ color: 'red' }}>￥{record.payAmount}</span>
            </div>
          </>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      render: (record: any) => {
        let text = '';
        let key = '';
        title.map((item) => {
          if (record == item.key) {
            text = item.title;
            key = item.key;
          }
        });
        return (
          <Tag color="magenta" key={key}>
            {text}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'actions',
      render: (record: any) => {
        if (record.orderStatus == 1) {
          return (
            <Button
              type="primary"
              onClick={() => {
                show('2', record);
              }}
            >
              备注
            </Button>
          );
        }

        if (record.orderStatus == 2) {
          return (
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  show('1', record);
                }}
              >
                发货
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  show('3', record);
                }}
              >
                修改自提点
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  show('2', record);
                }}
              >
                备注
              </Button>
            </Space>
          );
        }

        if (record.orderStatus != 9) {
          return (
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  show('2', record);
                }}
              >
                备注
              </Button>
              <Popconfirm
                title="您确定是要退货吗?"
                onConfirm={() => {
                  confirm(record);
                }}
                okText="退货"
                cancelText="取消"
              >
                <Button type="primary" danger>
                  一键退货
                </Button>
              </Popconfirm>
            </Space>
          );
        }

        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                show('2', record);
              }}
            >
              备注
            </Button>
          </Space>
        );
      },
    },
  ];

  const column = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (_: any, record: any) => <span>{record.name}</span>,
    },
    {
      title: '自提地住址',
      dataIndex: 'address',
      key: 'address',
      render: (_: any, record: any) => <span>{record.address}</span>,
    },
    {
      title: '操作',
      render: () => {
        return (
          <>
            <Button type="primary" ghost onClick={choice}>
              选择
            </Button>
          </>
        );
      },
    },
  ];

  function onSearch(value: any) {
    selectAll({
      page: 1,
      limit: 4,
      where: { address: value, name: updateName },
    }).then((res: any) => {
      console.log(res);
      setDataSource(res.result);
    });
    console.log(value, 8888888);
  }
  function choice() {
    console.log(123);
  }
  return (
    <div className="order">
      <Form
        layout="inline"
        initialValues={{ remember: true }}
        className="Form"
        onFinish={onFinish}
      >
        <Form.Item name="orderNumber">
          <div>
            <Select defaultValue="订单号" style={{ width: 100 }}>
              <Option value="0">订单号</Option>
              <Option value="1">买家姓名</Option>
              <Option value="2">买家电话</Option>
            </Select>
            <Input style={{ width: '50%' }} placeholder="请输入内容" />
          </div>
        </Form.Item>

        <Form.Item label="日期:" name="time">
          <RangePicker
            showTime={{
              format: 'YYYY-MM-DD HH:mm',
            }}
          />
        </Form.Item>
        <Form.Item label="订单状态:" name="orderStatus" initialValue="0">
          <Select style={{ width: 150 }} onChange={handleChange}>
            <Option value="0">全部</Option>
            <Option value="1">待付款</Option>
            <Option value="2">待发货</Option>
            <Option value="3">已发货</Option>
            <Option value="4">已完成</Option>
            <Option value="5">待评价</Option>
            <Option value="6">已取消</Option>
            <Option value="7">已删除</Option>
            <Option value="8">拼团中</Option>
            <Option value="9">一键退款</Option>
            <Option value="10">同意退款</Option>
            <Option value="11">拒绝退款</Option>
            <Option value="12">退款中</Option>
            <Option value="13">已退款</Option>
          </Select>
        </Form.Item>
        <Form.Item label="用户ID:" name="id">
          <Input placeholder="请输入内容" className="antInput" />
        </Form.Item>
        <Form.Item label="商品名称:" name="tradeName">
          <Input placeholder="请输入内容" className="antInput" />
        </Form.Item>

        <Form.Item label="自提点:" name="location">
          <Input placeholder="请输入自提点" className="antInput" />
        </Form.Item>

        <Button type="primary" htmlType="submit">
          搜索
        </Button>
      </Form>
      <Tabs defaultActiveKey="0" onChange={callback}>
        {titleList.map((item) => {
          return <TabPane tab={item.title} key={item.key} />;
        })}
      </Tabs>
      <Table
        columns={columns}
        expandable={{
          expandedRowRender: (record: any) => {
            return (
              <div className="content">
                <div>
                  订单号:{' '}
                  <span style={{ color: '#9cbd71' }}>{record.orderNumber}</span>{' '}
                </div>
                <div>{record.createdAt}</div>
                <div>团长姓名:{record.headName}</div>
                <div>小区:{record.housingEstate}</div>
                <div>地址:{record.location}</div>
                <div>备注:{record.remarks}</div>
              </div>
            );
          },
        }}
        dataSource={data}
        pagination={pagination}
      />
      ,
      <Modal
        title="快递发货"
        visible={hair}
        cancelText="取消"
        okText="发货"
        onOk={send}
        onCancel={() => {
          handleCancel('1');
        }}
      >
        <Radio.Group onChange={onChange} value={radio}>
          <Radio value={3}>发货</Radio>
          <Radio value={2}>不发货</Radio>
        </Radio.Group>
      </Modal>
      <Modal
        title="备注"
        visible={remarks}
        cancelText="取消"
        okText="提交"
        onOk={submit}
        onCancel={() => {
          handleCancel('2');
        }}
      >
        <TextArea rows={4} onBlur={GetTextArea} />
      </Modal>
      <Modal
        title="选择自提点"
        visible={update}
        onCancel={() => {
          handleCancel('3');
        }}
        footer={null}
      >
        <Search placeholder="请输入内容" onSearch={onSearch} enterButton />
        <Table columns={column} dataSource={dataSource} />,
      </Modal>
    </div>
  );
}
